import React, { useEffect, useState } from 'react';
import { Card, Table, Input, Select, Button, message, Popconfirm } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { getOrderList, configOrder, sendOrder, closeOrder } from '../../services/order';
import { HomeOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';

export interface Order {
  orderId: number;
  orderNo: string;
  userId: number;
  totalPrice: number;
  payStatus: number;
  payType: number;
  payTime: string;
  orderStatus: number;
  orderStatusString: string;
  extraInfo: string;
  isDeleted: number;
  createTime: string;
  updateTime: string;
}

const OrderAdmin = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [orderNo, setOrderNo] = useState<number>()
  const [orderStatus, setOrderStatus] = useState<number>()

  const fetchData = () => {
    setLoading(true);
    const params: API.OrderAdminParams= {
      pageNumber: pagination.current as number,
      pageSize: pagination.pageSize as number,
    }
    if(orderNo) {
      params.orderNo = orderNo;
    }
    params.orderStatus = orderStatus;
    getOrderList(params).then((res) => {
      setOrders(res.data?.list || []);
      setPagination({
        ...pagination,
        total: res.data?.totalCount,
      });
      setLoading(false);
    });
  };

  const handleConfig = () => {
    if (!selectedRowKeys.length) {
      message.error('请选择项');
      return;
    }
    configOrder(selectedRowKeys).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  const handleConfigOne = (ids) => {
    configOrder(ids).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  const handleSend = () => {
    if (!selectedRowKeys.length) {
      message.error('请选择项');
      return;
    }
    sendOrder(selectedRowKeys).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  const handleSendOne = (ids) => {
    sendOrder(ids).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  const handleClose = () => {
    if (!selectedRowKeys.length) {
      message.error('请选择项');
      return;
    }
    closeOrder(selectedRowKeys).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  const handleCloseOne = (ids) => {
    closeOrder(ids).then((res) => {
      if (res.resultCode === 200) {
        message.success(res.message);
        fetchData();
      } else {
        message.error(res.message);
      }
    });
  }

  useEffect(() => {
    fetchData();
  }, [JSON.stringify(pagination)]);


  const status = {
    0: '待支付',
    1: '已支付',
    2: '配货完成',
    3: '出库成功',
    4: '交易成功',
    '-1': '手动关闭',
    '-2': '超时关闭',
    '-3': '商家关闭'
  }

  const columns: ColumnsType<Order> = [
    {
      title: '订单号',
      key: 'orderNo',
      dataIndex: 'orderNo',
    },
    {
      title: '订单总价',
      dataIndex: 'totalPrice',
    },
    {
      title: '订单状态',
      render: (_, record: Order) => {
        return status[record.orderStatus];
      },
    },
    {
      title: '支付方式',
      render: (_, record: Order) => {
        if (record.payStatus === 1) {
          return '微信支付';
        } else if (record.payStatus === 2) {
          return '支付宝支付';
        }
        return '-----'
      },
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (_, item: Order) => {
        return (
          <>
            {item.orderStatus === 1 && (
              <Popconfirm
                title="确定配货完成吗？"
                onConfirm={() => handleConfigOne([item.orderId])}
                okText="确定"
                cancelText="取消"
              >
                <a style={{ cursor: 'pointer', marginRight: '10px' }}>配货完成</a>
              </Popconfirm>
            )}
            {item.orderStatus === 2 && (
              <Popconfirm
                title="确定出库吗？"
                onConfirm={() => handleSendOne([item.orderId])}
                okText="确定"
                cancelText="取消"
              >
                <a style={{ cursor: 'pointer', marginRight: '10px' }}>出库</a>
              </Popconfirm>
            )}
            {!(item.orderStatus === 4 || item.orderStatus < 0) && (
              <Popconfirm
                title="确定关闭订单吗？"
                onConfirm={() => handleCloseOne([item.orderId])}
                okText="确定"
                cancelText="取消"
              >
                <a style={{ cursor: 'pointer', marginRight: '10px' }}>关闭订单</a>
              </Popconfirm>
            )}
            {<a style={{ cursor: 'pointer', marginRight: '10px' }} onClick={() => {
              history.push(`/admin/order/${item.orderId}`)
            }}>订单详情</a>}
          </>
        );
      }
    }
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <Card>
      <div>
          <Input
            allowClear
            placeholder="请输入商品名称"
            onChange={(e) => {
              setOrderNo(Number(e.target.value))
            }}
            style={{ width: 200, marginRight: '10px' }}
          />
          <span style={{ marginRight: '5px' }}>订单状态</span>
          <Select
            style={{ width: 120 }}
            allowClear
            defaultValue={''}
            options={[{
              value: '',
              label: '全部'
            }, {
              value: 0,
              label: '待支付'
            }, {
              value: 1,
              label: '已支付'
            }, {
              value: 2,
              label: '配货完成'
            }, {
              value: 3,
              label: '出库成功'
            }, {
              value: 4,
              label: '交易成功'
            }, {
              value: -1,
              label: '手动关闭'
            }, {
              value: -2,
              label: '超时关闭'
            }, {
              value: -3,
              label: '商家关闭'
            }]}
            onChange={(value) => {
              setOrderStatus(value);
            }}
          />
          <Button
            type='primary'
            onClick={() => {
              fetchData();
            }}
            style={{ marginLeft: '10px', marginBottom: '10px' }}
          >
            搜索
          </Button>
          <Button
            type='primary'
            icon={<HomeOutlined />}
            onClick={handleConfig}
            style={{ marginLeft: '10px', marginBottom: '10px' }}
          >
            配货
          </Button>
          <Button
            type='primary'
            icon={<HomeOutlined />}
            onClick={handleSend}
            style={{ marginLeft: '10px', marginBottom: '10px' }}
          >
            出库
          </Button>
          <Button
            danger
            onClick={handleClose}
            style={{ marginLeft: '10px', marginBottom: '10px' }}
          >
            关闭订单
          </Button>
        </div>
      <Table
        columns={columns}
        rowKey={'orderId'}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => {
            setPagination({
              ...pagination,
              current: page,
              pageSize,
            });
          },
        }}
        rowSelection={rowSelection}
        dataSource={orders}
        loading={loading}
      />
    </Card>
  );
};

export default OrderAdmin;
